import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import Message.CheckDTO;
import Message.StuMessageDTO;
import httpclient.QuickStart;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;


/**
 * @author liushan
 * Created by liushan on 2019-04-09.
 */
@WebServlet(urlPatterns = {"/login/dgut"})
public class myServlet extends HttpServlet {

    // curl -v http://localhost:8080/test/Servlet1
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        doPost(req,resp);
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        Jsonb jsonb = JsonbBuilder.create();
        String token = req.getParameter("token");
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("token", token));
        formparams.add(new BasicNameValuePair("appid", "javaee"));
        formparams.add(new BasicNameValuePair("appsecret", "b3b52e43ccfd"));
        formparams.add(new BasicNameValuePair("userip", "10.0.2.2"));

        String check = QuickStart.post("https://cas.dgut.edu.cn/ssoapi/v2/checkToken",formparams);
        CheckDTO checkDTO = jsonb.fromJson(check,CheckDTO.class);
        if(checkDTO.getOpenid()==null)
        {
            System.out.println("验证失败!");
            resp.sendRedirect("https://cas.dgut.edu.cn?appid=javaee&state=STATE");
        }
        //resp.getWriter().println(jsonb.toJson(checkDTO));
        formparams.clear();
        formparams.add(new BasicNameValuePair("access_token", checkDTO.getAccess_token()));
        formparams.add(new BasicNameValuePair("openid", checkDTO.getOpenid()));
        String Stumessage = QuickStart.post("https://cas.dgut.edu.cn/oauth/getUserInfo",formparams);

        StuMessageDTO stuMessageDTO = jsonb.fromJson(Stumessage, StuMessageDTO.class);
        if(stuMessageDTO.getUsername()==null)
        {
            System.out.println("验证失败!");
            resp.sendRedirect("https://cas.dgut.edu.cn?appid=javaee&state=STATE");
        }
        //resp.getWriter().println(jsonb.toJson(stuMessageDTO));
        HttpSession session = req.getSession(true);
        session.setAttribute("islogin",stuMessageDTO);
        resp.sendRedirect("http://localhost:8080/DGUTLogin.jsp");
    }
}
